package com.harvey.study.data.structure.datastructure.linkedlist;

import lombok.Data;

/**
 * date: 2021-04-21 版本2
 * desc: 单向链表 头结点为特殊节点
 */
@Data
public class SingledLinkedListV2<T> {
    private int length; // 链表长度
    private Node<T> head; //链表头部节点

    public SingledLinkedListV2() {
        this.head = new Node<T>();
    }

    /**
     * 添加到指定位置
     * @param data
     * @param pos
     * @return
     */
    public boolean add(T data,int pos){
        checkPos(pos);
        int index = 1;
        Node<T> p = head;
        Node<T> q = head.next;
        while(index++<pos){
            p = q;
            q = p.next;
        }
        p.next = new Node<>(data,q);
        length++;
        return true;
    }

    /**
     * 从后方添加
     * @param data
     * @return
     */
    public boolean add(T data){
        return add(data,length+1);
    }

    /**
     * 删除指定位置节点
     * @param pos
     * @return
     */
    public T remove(int pos){
        checkPos(pos);
        int index = 1;
        Node<T> p = head;
        Node<T> q = head.next;
        while(index++<pos){
            p = q;
            q = p.next;
        }
        p.next = q.next;
        length--;
        return q.data;
    }

    /**
     * 查找指定位置节点
     * @param pos
     * @return
     */
    public T find(int pos){
        checkPos(pos);
        int index = 1;
        Node<T> p = head.next;
        while(index++<pos){
            p = p.next;
        }
        return p.data;
    }

    /**
     * 修改指定位置节点
     * @param obj
     * @param pos
     * @return
     */
    public boolean modify(T obj,int pos){
        checkPos(pos);
        int index = 1;
        Node<T> p = head.next;
        while(index++<pos){
            p = p.next;
        }
        p.data = obj;
        return true;
    }

    /**
     * 判断链表是否为null
     * @return
     */
    public boolean isEmpty(){
        return length == 0;
    }

    /**
     * 获取链表长度
     * @return
     */
    public int size(){
        return length;
    }

    /**
     * 清空链表
     */
    public void clear(){
        length = 0;
        head.next = null;
    }


    private void checkPos(int pos){
        if(pos<1 || pos>length+1){
            throw new RuntimeException("pos不合法");
        }
    }

    public static void main(String[] args) {
        SingledLinkedListV2<String> linkedListV2 = new SingledLinkedListV2<String>();
    
        linkedListV2.add("1",1);
        linkedListV2.add("2",2);
        linkedListV2.add("3",3);

        // linkedListV2.remove(3);
        // linkedListV2.remove(2);


        Node<String> head = linkedListV2.head;

        while(head.next!=null){
            head = head.next;
            System.out.println(head.data);
        }
        

    }
}
